Original title: "Dissecting the Qilin protocol"
Original source: 0xkowloon
Original translation: 0x33, Rhythm BlockBeats
Qilin Protocol is a decentralized volatility protocol. Its emergence began with a group of netizens on the encrypted online chat platform Codex. They first learned about DeFi in 2020 and found a way to introduce derivatives trading into long-tail assets of cryptocurrencies, thus Qilin Protocol was born.
Qilin is essentially a derivatives trading protocol that allows traders to use leverage.
Its main features include:
️ Provide up to 100 times long or short leverage.
LS tokens can Class A (ALP) or Class B (BLP).
Level A is a risk appetite Low LP
It has the following characteristics:
· Can share 15% of LP profits;
· No upper limit;
· Unused liquidity can be deposited into other Agreement to generate income;
· When the trading pair has a high open position, it can be converted to BLP. The purpose is to cover unhedged positions. When the size of the open interest declines, these BLPs will return to A grade.
Class B is an LP with a higher risk preference
B grade p>
It has the following characteristics:
Shareable 85% LP Profit;
· $1 million cap. Considering a 10% long/short spread, this cap supports $19-21 million in trading volume;
· Allows traders to take positions from different positions.
The price of LS tokens is directly proportional to the value of LP. As the scale of LPs in the agreement grows, token holders will benefit from it. If LPs are at a loss, LS tokens can be purchased at a discounted price to incentivize more deposits.
LS Token Price = LP Value ÷ LS Token Supply
Pass every 8 Hourly check the imbalance ratio of long and short positions to calculate the deviation rate. If the rate is above the imbalance threshold, a rebase funding rate is triggered and the fee is transferred to LPs.

Sliding dynamic index measured is the risk of open positions to liquidity. The smaller the index, the greater the decline. This is because the exponent will be multiplied by a constant k, the smaller the k, the less liquid. As the size of unhedged positions grows, a larger drawdown is needed to narrow the imbalance. Large unhedged positions can result in loss of funds.

The main entry points of Qilin are Fluidity.sol and Exchange.sol. LPs can provide liquidity through Fluidity.sol, and mint and burn LS tokens in FundToken.sol. Traders can open or close positions through Exchange.sol. The liquidator can close the position through Liquidation.sol.
The data of the entire agreement is stored in Depot.sol, and the owner can modify the agreement in SystemSetting.sol configuration.
#initialFunding In order to initialize a liquidity pool, funding must be called. It checks that the system is active, the initial funding is complete, and the total supply of LS tokens is within the maximum initial liquidity fund, then adds liquidity to the repository, transfers LP's USDC to the pool and mints LS tokens.
During the initial funding period, the exchange rate between USDC and LS tokens was 1:1. Repository addresses are imported into liquidity contracts via AddressResolver#importAddresses .

Once the initial funding cap is reached, the fund can be closed by calling liquidity #closeInitialFunding. It sets the _initialFundingCompleted flag in the Depot to true.

After the initial funding phase, LPs can fund the liquidity pool by calling #fundLiquidity. It behaves similarly to initialFunding, except that it requires the funding period to be complete and the exchange rate is no longer 1:1.

The price of LS tokens is equal to the USDC value of the liquidity pool divided by the total supply of LS tokens.

The new USDC value in the pool cannot exceed the margin ratio of the total position size in the repository.

Traders can open leveraged positions by calling Exchange#openPosition.
The leverage level must be within the allowed level range, and the position size must be greater than the minimum margin amount.

The direction of the long line is 1 and the direction of the short line is 2.

The exchange gets the spot price from the ExchangeRate contract, which it then uses as the opening price for the position. This price is available from the oracle.

The exchange opens a new position in the repository, the margin is transferred from the trader to the repository, and the trader's share and size are calculated.
If:
1 ETH = 2,500 USDC
Margin= 5,000 USD
Leverage= 100x
Total leverage of long positions in the pool=100,000,000 USDC
Total share of bulls=100
Then your:
Leverage position=500,000 USDC
Equity=100,000,000 ÷ 100 = 1,000,000 (Equity is per share leverage position)
share = 5,000 ÷ 1,000,000 = 0.005
size = 5,000 ÷ 2,500 = 2

It will The trader's position is added to the repository's summary and a new position record is added to the repository.

A trader's position status can be checked by calling Liquidation#alertLiquidation.
It retrieves the PnL of the position, then after (plus profit/deduction of loss) and deduction of service charge and margin loss , to check that the minimum margin ratio for the position remains the same.
If the system has a closing fee, then there is a service fee, which is the trader's leveraged position times In percentage of closing fee.

The trader's net profit can be obtained by calling Depot#calNetProfit. A trader makes a profit if the spot price is higher than the open price for a long position, or if the spot price is lower than the open price for a short position. Net profit is the leveraged position times the spread divided by the open price.

< /p>
If the current ETH price is 3000 USDC, the net profit is
p>

Trader's profit loss can be compensated by calling Depot#calMarginLoss. Margin loss cannot exceed the trader's leveraged position (meaning it can be 0, but not negative). It is equal to the trader's leveraged position minus his share equity.

According to the above data, the profit loss will be

If margin + profit/loss is greater than service fee + Margin loss, check if the amount is less than the minimum percentage of margin. Otherwise, no check is made, since the position has actually been liquidated (see Liquidation#alertBankruptedLiquidation).

If a trader's margin is lower than the agreed margin ratio requirement, he needs to replenish the margin. Otherwise, he will face the risk of being liquidated. This can be achieved by calling Exchange#addDeposit.
The additional margin must exceed the system's minimum additional storage requirements.

Once the requirement is clarified, it transfers the additional margin to the warehouse and updates the warehouse's summary.

LPs with more than the minimum LS token requirement are entitled to liquidate positions by calling Liquidation#liquidate.
The first thing to check is that msg.sender has enough LS tokens to enjoy this entitlement.

The contract will then calculate the service fee for liquidation, profit loss and PnL. The formula is the same as Liquidation#alertLiquidation.

Profit (+profit or -loss) must include service charges and loss of profit. Otherwise the position cannot be liquidated (must be liquidated by calling Liquidation#alertBankruptedLiquidation).

The final margin must be lower than the minimum margin ratio after considering all variables, otherwise the liquidation cannot be completed.

The liquidation reward is the profit (+ profit or - loss) after deducting the service fee and profit loss

The contract then updates the repository summary content.
First, it updates the liquidity pool.
· This fee is added to the liquidity pool.
· If the position is profitable, deduct the profit from the liquidity pool.
· If the position is not profitable, add the loss to the liquidity pool.
· Deduct any (margin loss - position margin, min 0) from the liquidity pool.

Total margin increased (margin loss - position margin).

The total leveraged position reduces the share value of that position, and those shares are removed.

The total size is reduced by the position size due to the position at which the position was opened multiplied by the remaining rebase rate (taking into account the change in funding rate between opening and closing).

Finally, the liquidation reward is transferred to the liquidator and the position is deleted.

Liquidation#bankruptedLiquidate There are not many special liquidation steps, and its liquidation operation is similar to normal liquidation. The key difference is
1. The Margin (+Profit or -Loss) must be insufficient to cover the service fee and Margin Loss.
2. In this case, the liquidation fee is replaced by the liquidation fee, because the position cannot generate a fee, and the fee is equal to the margin of the position multiplied by the percentage of the liquidation fee.

The liquidity of the new pool is the current pool's liquidity +/- the difference between margin and margin loss, minus the liquidation fee.

Traders can close positions by calling Exchange#closePosition.
It gets the share value of the position (same formula), service fee (same formula) and profit margin loss (leveraged position - share value).

Whether the position is profitable or not, it will not be liquidated.

The value of the asset transferred back to the trader is equal to the margin (+profit or -loss) minus fees and margin losses. If the value is larger than what the liquidity pool (+margin) can cover, it is set to the latter value.
USDC is being transferred back to traders.
It is basically the same as liquidation, except the new liquidity pool value is the liquidity pool value plus fees (+transaction trader's loss or -trader's profit).
rebase happens every 8 hours Once, this can be done by calling Exchange#rebase. Only the key logic is discussed here. The setting.rebaseInterval time period must have run.
Update the new rebase time and state of the repository by recalculating the rebaseLeft (rebase funding rate) transaction.
In the repository, the total profit, the total leverage position and the total share are deducted by the rebase funding rate so that the Funds are transferred to the liquidity pool.
Qilin in its derivatives trading The peer-to-peer pool model is implemented in the protocol. It actively tries to protect its liquidity providers from unhedged positions by regularly adjusting the benchmark and applying a slippage dynamic sensitivity index. It also allows liquidity providers to choose the risk they are willing to take by joining different LP tranches. It is a competitive product of existing derivatives protocols.
Original link
Welcome to join the official BlockBeats community:
Telegram Subscription Group: https://t.me/theblockbeats
Telegram Discussion Group: https://t.me/BlockBeats_App
Official Twitter Account: https://twitter.com/BlockBeatsAsia